package com.xcode.example.common.utils;



import com.xcode.example.config.AppConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * Phantom生成页面截图工具类
 *
 * @author Administrator
 * @date 2020/11/18
 */
@Slf4j
public class PhantomTools {

    /**
     * Phantom可执行文件的路径
     */
    private static final String PHANTOMJS_PATH = AppConfig.getPhantomjsPath();
    /**
     * Phantom配置文件路径，即js代码
     */
    private static final String PHANTOMJS_CODE_PATH = AppConfig.getPhantomjsCodePath();
    /**
     * 完整的执行命令行
     */
    private static final String SHELL_COMMAND = PHANTOMJS_PATH + " " + PHANTOMJS_CODE_PATH + " ";
    private final String file;
    private String size = null;

    /**
     * 构造截图类
     * @param imgPath 临时文件地址
     * @param hash 用于临时文件的目录唯一化
     *
     */
    public PhantomTools(String imgPath, String hash) {
        this.file = imgPath + File.separator + hash + ".jpg";
    }

    /**
     * 构造截图类
     * @param hash 用于临时文件的目录唯一化
     * @param size 图片的大小，如800px*600px（此时高度会裁切），或800px（此时 高度最少=宽度*9/16，高度不裁切）
     */
    public PhantomTools(String imgPath, String hash, String size) {
        this(imgPath, hash);
        if (size != null) {
            this.size = " " + size;
        }
    }

    /**
     * 将目标网页转为图片字节流
     * @param url 目标网页地址
     * @return 字节流
     */
    public byte[] getByteImg(String url) {
        BufferedInputStream in = null;
        ByteArrayOutputStream out = null;
        File file = null;
        byte[] ret = null;
        try {
            if (exeCmd(SHELL_COMMAND + url + " " + this.file + (size != null ? size : ""))) {
                file = new File(this.file);
                if (file.exists()) {
                    out = new ByteArrayOutputStream();
                    byte[] b = new byte[5120];
                    in = new BufferedInputStream(new FileInputStream(file));
                    int n;
                    while ((n = in.read(b, 0, 5120)) != -1) {
                        out.write(b, 0, n);
                    }
                    ret = out.toByteArray();
                }
            } else {
                ret = new byte[] {};
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        return ret;
    }

    /**
     * 执行CMD命令
     */
    private static boolean exeCmd(String commandStr) {
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            if (p.waitFor() != 0 && p.exitValue() == 1) {
                return false;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return true;
    }
}
